package wnhz.com.business;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wnhz.com.business.base.BaseRVAdapter;
import wnhz.com.business.base.BaseViewHolder;
import wnhz.com.business.base.MyBaseActivity;
import wnhz.com.business.groupshop.bean.HomeIndexBean;
import wnhz.com.business.groupshop.bean.LableBean;
import wnhz.com.business.netcallback.DialogCallback;
import wnhz.com.business.shareshop.ShareShopActivity;
import wnhz.com.business.uitls.MyCallBack;
import wnhz.com.business.uitls.ToastUtils;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.XUtil;

/**
 * Created by lizhenglong on 2017-10-27 0027.
 * 职业标签
 */

public class LableActivity extends MyBaseActivity {

    @BindView(R.id.rl_register_back)//返回
            RelativeLayout rlRegisterBack;
    @BindView(R.id.title)//标题
            TextView title;
    @BindView(R.id.title_register_jump)//完成
            TextView titleRegisterJump;
    @BindView(R.id.ry_lablelist)//标签列表
            RecyclerView ryLablelist;
    private BaseRVAdapter adapter;
    private int type;
    private String sex = "";
    private String username = "";
    private String testpath = "";
    private String birthday = "";
    private String industryid = "";
    private String jobid = "";
    private String lableid = "";
    private List<LableBean.InfoBean> infoBeanList = new ArrayList<>();
    private Map<Object, Object> chosemap = new HashMap<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acticvity_lable);
        ButterKnife.bind(this);
        titleRegisterJump.setVisibility(View.VISIBLE);
        titleRegisterJump.setText("完成");
        type = getIntent().getIntExtra("type",1); //1 是注册时完善信息 2 修改个人信息
        sex = getIntent().getStringExtra("sex");// 性别  1男  2女
        username = getIntent().getStringExtra("username");//用户昵称
        testpath = getIntent().getStringExtra("head_img");//图片路径
        birthday = getIntent().getStringExtra("birth");//生日
        industryid = getIntent().getStringExtra("industry_id");//
        jobid = getIntent().getStringExtra("job_id");//职业ID
        LoadData();
    }

    private void LoadData() {
        Map<String, String> map = new HashMap<>();
        if (TextUtils.isEmpty(MyApplication.getInstance().getInfoBean().getToken())) {
            MyApplication.getInstance().BackLoginActivity();
            return;
        } else {
            infoBeanList.clear();
            map.put("token", MyApplication.getInstance().getInfoBean().getToken());
            map.put("type", "1");//1-标签  2-行业方向  3-职位
            OkGo.<String>post(Url.UCENTRER_GETLABELLIST)
                    .tag(this)
                    .params(map, false)
                    .execute(new DialogCallback<String>(this) {

                        @Override
                        public void onSuccess(Response<String> response) {
                            Log.e("标签数据", response.body().toString());
                            JSONObject jsonObject = null;
                            try {
                                jsonObject = new JSONObject(response.body().toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            String res = jsonObject.optString("re");
                            if (res.equals("1")) {
                                Gson gson = new Gson();
                                LableBean lableBean = gson.fromJson(response.body(), LableBean.class);
                                infoBeanList = lableBean.getInfo();
                                initList();
                            } else if ("-1".equals(jsonObject.optString("re"))){
                                MyToast(getResources().getString(R.string.login_out));
                                MyApplication.getInstance().gotoLoginActivity();
                            }else {
                                ToastUtils.showToast(LableActivity.this, "暂无数据");
                            }
                        }

                        @Override
                        public void onFinish() {
                            super.onFinish();
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                        }
                    });
        }
    }

    private void initList() {
        ryLablelist.setLayoutManager(new GridLayoutManager(LableActivity.this, 3, GridLayoutManager.VERTICAL, false));
        adapter = new BaseRVAdapter(LableActivity.this, infoBeanList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_lable;
            }

            @Override
            public void onBind(final BaseViewHolder holder, final int position) {
                if (infoBeanList.get(position).getStatus().equals("0")) {
                    holder.getImageView(R.id.item_lableimg).setImageResource(R.drawable.ic_dianpu_choise_gray);
                } else {
                    holder.getImageView(R.id.item_lableimg).setImageResource(R.drawable.ic_dianpu_choise_red);
                }
                holder.setTextView(R.id.item_lablename, infoBeanList.get(position).getName());
                holder.getView(R.id.rl_item_lable).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (infoBeanList.get(position).getStatus().equals("1")) {
                            infoBeanList.get(position).setStatus("0");
                            holder.getImageView(R.id.item_lableimg).setImageResource(R.drawable.ic_dianpu_choise_gray);
                            chosemap.remove(position);
                            notifyDataSetChanged();
                        } else {
                            infoBeanList.get(position).setStatus("1");
                            holder.getImageView(R.id.item_lableimg).setImageResource(R.drawable.ic_dianpu_choise_red);
                            chosemap.put(position, infoBeanList.get(position).getLabel_id());
                            notifyDataSetChanged();
                        }
                    }
                });
            }
        };
        ryLablelist.setAdapter(adapter);
    }

    @OnClick({R.id.rl_register_back, R.id.title_register_jump})
    void Click(View v) {
        switch (v.getId()) {
            case R.id.rl_register_back:
                finish();
                break;
            case R.id.title_register_jump:
                lableid = "";
                Iterator<Object> iterator = chosemap.keySet().iterator();
                while (iterator.hasNext()) {
                    lableid += chosemap.get(iterator.next()) + ",";
                }
                if (TextUtils.isEmpty(lableid)){
                    MyToast("请选择标签");
                    return;
                }
                uploadPersonInfo();
                break;
        }
    }

    @Override
    protected void handleMsg(Message msg) {

    }

    /*
    * 个人信息修改
       @param  str  username     用户昵称
       @param  str  head_img     头像
       @param  int  sex  	     性别  1男  2女
       @param  int  birth  	     生日
       @param  int  industry_id  行业id
       @param  int  job_id       职位id
       @param  str  label_id  	 标签id（逗号拼接）
       @param  str  token  		 用户token
*/
    private void uploadPersonInfo() {
        if (TextUtils.isEmpty(MyApplication.getToken())) {
            MyToast("获取信息失败");
            return;
        } else {
            File file = new File(testpath);
            String token = MyApplication.getToken();

            Map<String,Object> maps = new HashMap<>();
            maps.put("token",token);
            maps.put("sex",sex);
            maps.put("username",username);
            maps.put("birth",birthday);
            maps.put("industry_id",industryid);
            maps.put("job_id",jobid);
            maps.put("label_id",lableid);
            maps.put("head_img",file);
            XUtil.Post(Url.UCENTER_MODUSERINFO,maps,new MyCallBack<String>(){
                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);

                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        String re = jsonObject.optString("re");
                        String info = jsonObject.optString("info");
                        if (re.equals("1")) {
                            startActivity(new Intent(LableActivity.this, ShareShopActivity.class));
                            finish();
                        } else if ("-1".equals(jsonObject.optString("re"))){
                            MyToast(info);
                            MyApplication.getInstance().gotoLoginActivity();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFinished() {
                    super.onFinished();
                    Log.e("1TAG","1111");
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                    Log.e("onError","" + "222");
                }
            });

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
